"""
Main entry point for LogRun Manager with manual argument parsing.
"""

import sys
from typing import List, Optional

from .runner import CommandRunner
from .storage import LogStorage
from .cli import list_command, show_log_command, cleanup_command, stats_command, remove_log_command


def parse_arguments(args: List[str]) -> tuple:
    """
    Parse command line arguments manually.
    
    Returns:
        (management_command, command_args, tags, options)
    """
    i = 0
    tags = []
    management_cmd = None
    show_log_id = None
    delete_id = None
    live_mode = False
    remote_mode = False
    
    while i < len(args):
        arg = args[i]
        
        if arg == '--list' or arg == '-l':
            management_cmd = 'list'
            i += 1
        elif arg == '--show-log' or arg == '-s':
            management_cmd = 'show-log'
            if i + 1 < len(args) and not args[i + 1].startswith('-'):
                show_log_id = args[i + 1]  # Keep as string to support comma-separated values
                i += 2
            else:
                # Default to latest ID when no ID provided
                from .storage import LogStorage
                storage = LogStorage()
                # Apply tag filter if tags are specified
                tag_filter = tags[0] if tags else None
                entries = storage.get_entries(limit=1, tag_filter=tag_filter)
                if entries:
                    show_log_id = str(entries[0].id)
                    if tag_filter:
                        print(f"No ID provided, using latest log ID with tag '{tag_filter}': {show_log_id}")
                    else:
                        print(f"No ID provided, using latest log ID: {show_log_id}")
                    i += 1
                else:
                    if tag_filter:
                        print(f"Error: No logs found with tag '{tag_filter}' to show")
                    else:
                        print(f"Error: No logs found to show")
                    sys.exit(1)
        elif arg == '--cleanup':
            management_cmd = 'cleanup'
            i += 1
        elif arg == '--stats':
            management_cmd = 'stats'
            i += 1
        elif arg in ('--delete', '--rm', '-d'):
            management_cmd = 'delete'
            if '=' in arg and arg.startswith('--'):
                value = arg.split('=', 1)[1]
                if not value:
                    print("Error: --delete requires an ID")
                    sys.exit(1)
                delete_id = value
                i += 1
            else:
                if i + 1 < len(args) and not args[i + 1].startswith('-'):
                    delete_id = args[i + 1]
                    i += 2
                else:
                    print("Error: --delete requires an ID")
                    sys.exit(1)
        elif arg == '--tag':
            if i + 1 < len(args):
                tags.append(args[i + 1])
                i += 2
            else:
                print(f"Error: --tag requires a value")
                sys.exit(1)
        elif arg.startswith('--tag='):
            # Handle --tag=value format
            tag_value = arg[6:]  # Remove '--tag='
            if tag_value:
                tags.append(tag_value)
            i += 1
        elif arg == '--help' or arg == '-h':
            management_cmd = 'help'
            i += 1
        elif arg == '--live':
            live_mode = True
            i += 1
        elif arg == '--remote':
            remote_mode = True
            i += 1
        else:
            # Found the start of the actual command
            return management_cmd, args[i:], tags, {
                'show_log_id': show_log_id,
                'delete_id': delete_id,
                'live_mode': live_mode,
                'remote_mode': remote_mode
            }
    
    return management_cmd, [], tags, {
        'show_log_id': show_log_id,
        'delete_id': delete_id,
        'live_mode': live_mode,
        'remote_mode': remote_mode
    }


def show_help():
    """Show help message."""
    help_text = """
LogRun - Command execution with automatic logging and history management.

Usage:
  logrun [OPTIONS] <command> [args...]

Management Options:
  -l, --list              List recent log entries
  -s, --show-log ID[,ID...]       Show log content for specific ID(s), supports comma-separated values
  -d, --delete LOG-ID     Delete a run log and resequence IDs
  --cleanup               Clean up old log files
  --stats                 Show statistics
  --tag TEXT              Add tags to the command execution
  --live                  Show real-time output while logging (for interactive commands)
  --remote                Execute logrun command on remote server (SSH to kunshan)
  -h, --help              Show this help message

Examples:
  logrun gsm test-remote --solver=gcr --gpu=hip --debug
  logrun --tag=testing echo "Hello World"
  logrun --list
  logrun --show-log 5
  logrun --show-log 3,4,5
  logrun --remote --list                    # List logs on remote server
  logrun --remote --tag=hip ./test_hip_solvers.sh --solver=gcr
  logrun --stats
  logrun --cleanup

When the first parameter starts with '-', it's treated as a management option.
Otherwise, all parameters are treated as a command to execute with logging.
"""
    print(help_text.strip())


def execute_remote_command(management_cmd: Optional[str], command_args: List[str], 
                         tags: List[str], options: dict) -> int:
    """
    Execute logrun command on remote server via SSH.
    
    Args:
        management_cmd: Management command (list, show-log, etc.)
        command_args: Command arguments for execution
        tags: Tags for the command
        options: Parsed options including show_log_id
        
    Returns:
        Exit code from remote execution
    """
    import subprocess
    
    # Build remote logrun command
    remote_cmd = ['logrun']
    
    # Add tags
    for tag in tags:
        remote_cmd.append(f'--tag={tag}')
    
    # Add management commands
    if management_cmd == 'list':
        remote_cmd.append('--list')
    elif management_cmd == 'show-log':
        show_log_id = options.get('show_log_id')
        if show_log_id:
            remote_cmd.append(f'--show-log {show_log_id}')
    elif management_cmd == 'cleanup':
        remote_cmd.append('--cleanup')
    elif management_cmd == 'stats':
        remote_cmd.append('--stats')
    elif management_cmd == 'delete':
        delete_id = options.get('delete_id')
        if delete_id:
            remote_cmd.append(f'--delete {delete_id}')
    elif management_cmd == 'help':
        remote_cmd.append('--help')
    else:
        # Regular command execution
        remote_cmd.extend(command_args)
    
    # Join command parts and execute via SSH
    full_remote_cmd = ' '.join(remote_cmd)
    ssh_cmd = ['ssh', 'kunshan', full_remote_cmd]
    
    print(f"🌐 Executing remotely: {full_remote_cmd}")
    
    try:
        result = subprocess.run(ssh_cmd, text=True)
        return result.returncode
    except Exception as e:
        print(f"❌ Remote execution failed: {e}")
        return 1


def main():
    """Main entry point."""
    if len(sys.argv) == 1:
        show_help()
        return
    
    # Parse arguments
    args = sys.argv[1:]
    management_cmd, command_args, tags, options = parse_arguments(args)
    
    storage = LogStorage()
    
    # Handle remote execution first (before local management commands)
    if options.get('remote_mode', False):
        exit_code = execute_remote_command(management_cmd, command_args, tags, options)
        sys.exit(exit_code)
    
    # Handle local management commands
    if management_cmd == 'help':
        show_help()
        return
    elif management_cmd == 'list':
        # Use first tag as filter if multiple tags are provided
        tag_filter = tags[0] if tags else None
        list_command(storage, tag_filter=tag_filter)
        return
    elif management_cmd == 'show-log':
        show_log_command(storage, options['show_log_id'])
        return
    elif management_cmd == 'cleanup':
        cleanup_command(storage)
        return
    elif management_cmd == 'stats':
        stats_command(storage)
        return
    elif management_cmd == 'delete':
        if not options.get('delete_id'):
            print("Error: No log ID provided for delete command")
            sys.exit(1)
        try:
            target_id = int(options['delete_id'])
        except ValueError:
            print(f"Error: Invalid log ID '{options['delete_id']}'")
            sys.exit(1)
        remove_log_command(storage, target_id)
        return
    
    # If we have command arguments, execute them locally
    if command_args:
        runner = CommandRunner()
        exit_code, entry = runner.run_command(command_args, tags, live_mode=options.get('live_mode', False))
        sys.exit(exit_code)
    
    # No command provided, show help
    show_help()


if __name__ == '__main__':
    main()
